<?php

/**
 * Description of Util
 *
 * @author HEO
 */
class Util {

    public static function t($string, $params = array(), $category = 'Label') {
        Yii::import('application.modules.admin.models.Translate');

        $language = Yii::app()->language;
        $cache_id = sprintf('translations_%s_%s', $language, $category);

        $messages = false;
        if (Yii::app()->cache)
            $messages = Yii::app()->cache->get($cache_id);

        if ($messages === false) {
            $translations = Translate::model()->findAll('category = :category AND language_code = :language', array(
                ':category' => $category,
                ':language' => $language
                    ));
            $messages = array();
            foreach ($translations as $row) {
                $messages[$row->message] = $row->translation;
            }

            if (Yii::app()->cache)
                Yii::app()->cache->set($cache_id, $messages, Yii::app()->params['caching_time']);
        }

        if (isset($messages[$string]))
            return strtr($messages[$string], $params);
        else
            return strtr($string, $params);
    }

    public static function toAscii($str) {
        $str = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/", 'a', $str);
        $str = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $str);
        $str = preg_replace("/(ì|í|ị|ỉ|ĩ)/", 'i', $str);
        $str = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o', $str);
        $str = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $str);
        $str = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", 'y', $str);
        $str = preg_replace("/(đ)/", 'd', $str);
        $str = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", 'A', $str);
        $str = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', $str);
        $str = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $str);
        $str = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", 'O', $str);
        $str = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $str);
        $str = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", 'Y', $str);
        $str = preg_replace("/(Đ)/", 'D', $str);
        $str = ereg_replace("[-.,]", "", $str);
        $str = ereg_replace("[^ A-Za-z0-9]", " ", $str);
        return $str;
    }

    public static function toAlias($str) {
        $str = self::toAscii($str);
        $word_list = split(' ', $str);
        $str = '';
        foreach ($word_list as &$word) {
            if ($word != '')
                $str .= '-' . $word;
        }
        return trim(strtolower(substr($str, 1, strlen($str))));
    }

    public static function getFileExtension($filename) {
        return strtolower(substr($filename, strpos($filename, '.') + 1));
    }

    public static function getIP() {

        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }

    public static function foramtInputDate($date) {
        return substr($date, 6, 4) . "-" . substr($date, 3, 2) . "-" . substr($date, 0, 2);
    }

    public static function formatOutputDate($date) {
        return substr($date, 7, 2) . "-" . substr($date, 5, 0) . "-" . substr($date, 0, 4);
    }

    /**
     * return the date by specify the currency format, and flagmen
     * @date: date value
     * @format: currency format (include: YYYY/mm/dd or dd/mm/YYYY)
     */
    public static function getDateElement($date, $currency, $specify) {
        $foramt = Util::getCurrencyFormat($currency);

        if ($foramt == 'YYYY/mm/dd') {
            if ($specify == 'd')
                return substr($date, 8);
            else if ($specify == 'm')
                return substr($date, 5, 2);
            else if ($specify == 'y')
                return substr($date, 0, 4);
            else
                return 0;
        }
        else if ($foramt == 'dd/mm/YYYY') {
            if ($specify == 'd')
                return substr($date, 0, 2);
            else if ($specify == 'm')
                return substr($date, 3, 2);
            else if ($specify == 'y')
                return substr($date, 6);
            else
                return 0;
        }else {  //  mm/dd/YYYY
            if ($specify == 'd')
                return substr($date, 3, 2);
            else if ($specify == 'm')
                return substr($date, 0, 2);
            else if ($specify == 'y')
                return substr($date, 6);
            else
                return 0;
        }
        return 0;
    }

    /**
     * return the currency format of date time
     * @currency: currency value
     * @return: return format YYYY/mm/dd for Zh-Cn or dd/mm/YYYY for Vi-vn or mm/dd/YYYY for En-en     * 
     */
    public static function getCurrencyFormat($currency) {
        if ($currency == 'zh_cn')
            return 'YYYY/mm/dd';
        else if ($currency == 'vi')
            return 'dd/mm/YYYY';
        else
            return 'mm/dd/YYYY';
    }

    /**
     * return the format out put date in currency
     * @currency: currency value
     * @return d-m-Y OR m-d-Y OR Y-m-d in DATE
     */
    public static function getCurrencyFormatOutput($currency) {
        if ($currency == 'zh_cn')
            return 'Y-m-d';
        else if ($currency == 'vi')
            return 'd-m-Y';
        else
            return 'm-d-Y';
    }

    public static function getQouteStatus($status, $role = null) {
        switch ($status) {
            case 1:
                $sta = Util::t('Waiting', array(), 'Label');
                break;
            case 2:
                $sta = Util::t('Confirm', array(), 'Label');
                break;
            case 3:
                $sta = Util::t('Resolved', array(), 'Label');
                break;
            case 4:
                $sta = Util::t('Final Request', array(), 'Label');
                break;
            case 5:
                $sta = Util::t('Temprory Save', array(), 'Label');
                break;
            case 6:
                $sta = Util::t('Waiting Receive Deposit', array(), 'Label');
                break;
            case 7:
                $sta = Util::t('Received Deposit', array(), 'Label');
                break;
            case 8:
                if ($role == 'Saler')
                    $sta = Util::t('Require Update Sale Price', array(), 'Label');
                else
                    $sta = Util::t('Updated Purchase Price', array(), 'Label');
                break;
            case 9:
                $sta = Util::t('Updated Sell Price', array(), 'Label');
                break;
            case 10:
                $sta = Util::t('Finished', array(), 'Label');
                break;
            case 11:
                $sta = Util::t('Cancelled', array(), 'Label');
                break;
            case 12:
                $sta = Util::t('Pendng Debt', array(), 'Label');
                break;
        }
        return $sta;
    }

    public static function getListQuoteStatus($optionsQuote) {
        $listStatus = CHtml::openTag('select', array(
                    'name' => 'Quote[status]',
                    'id' => 'Quote_status',
                ));
        $listStatus .= CHtml::tag('option', array('value' => '0'), Util::t('All'), true);
        foreach ($optionsQuote as $key => $value)
            $listStatus .= CHtml::tag('option', array('value' => $key), Util::t($value), true);
//        $listStatus .= CHtml::tag('option', array('value' => 1), Util::t('Waiting'), true);        


        return $listStatus .= CHtml::closeTag('select');
    }

    public static function formatOutputCurrencyDate($time) {
        $locale = Util::getCurrencyFormatOutput(Yii::app()->language);

        if ($time > 0)
            return date($locale, $time);
        else
            return '---';
    }

    public static function getRole() {
        return Yii::app()->getModule('user')->getRole();
    }

    public static function getListAlphaChars($columnName) {
        $options = array();
        $options[''] = Util::t('Empty Value');
        for ($i = 65; $i <= 90; $i++) {
            $x = chr($i);
            $options[$columnName . '_' . $x] = $x;
        }
        return $options;
    }

    public static function getLanguage() {
        $language = Language::model()->findAll(array(
            'condition' => 'code != \'en\''
                ));
        return $language;
    }

    /**
     * generate a object code with prefix as a param
     */
    public static function generalNewID($lastID, $prefixChar) {
        if ($lastID != null) {
            $prefix = "";
            while (strlen($lastID) < 5) {
                $prefix .= 0;
                $lastID = $prefix . $lastID;
                $prefix = "";
            }

            return $prefixChar . $lastID;
        }
    }

    /**
     * Get User fullname
     */
    public static function listTrackingAdmin() {
        return $model = User::model()->getUserFullName();
    }

    /**
     * Get User fullname by is
     */
    public static function userFullNameByID($id) {
        Yii::import('application.modules.user.models.Profile');
        $model = $model = Profile::model()->findByPk($id);

        if ($model === NULL)
            return Util::t("Null Value");

        return $model->lastname . " " . $model->firstname;
    }

    /**
     * Porpost to generate a field name in ajax add more object field content in create/update supplier form (_form.php)
     * replace all space to underline char
     */
    public static function generalFieldAlias($fieldName) {
        return $fieldName = str_replace(' ', '_', $fieldName);
    }

    /**
     * Rewrite database field for output client
     * @params $field: Field in database
     * @params $keyTerm: prefix key term
     * @params $rewriteField: rewrite to virtual field in view 
     */
    public static function rewriteDBField($field, $keyTerm=null, $rewriteVirtualField=null) {
        $field = (preg_match('/_/', $field)) ? str_replace('_', ' ', ucwords($field)) : ucwords($field);

        if ($keyTerm != null && !preg_match('/' . $keyTerm . '/', $field)) {
            if (is_array($rewriteVirtualField)) {
                if (array_key_exists($field, $rewriteVirtualField)) {
                    return Util::t(ucwords($rewriteVirtualField[$field] . " " . $field), array(), 'Model');
                }
            } else {
                return Util::t(ucwords($keyTerm . " " . $field), array(), 'Model');
            }
        } else {
            if (is_array($rewriteVirtualField)) {
                if (array_key_exists($field, $rewriteVirtualField))
                    return Util::t(ucwords($rewriteVirtualField[$field]), array(), 'Model');
            }else
                return Util::t(ucwords($field), array(), 'Model');
        }
    }

    /**
     * List object fields in database
     * @params object: model tobe init
     * @params $igonredList: ignore fields
     * @params $keyTerm: prefix key 
     */
    public static function listDatabaseField($object, $ignoredList=null, $keyTerm=null, $rewriteVirtualField=null) {
        $model = new $object;
        $keys = array_keys($model->attributes);
        $option = "<select name='searchOption'><option value='all'>" . Util::t('All') . "</option>";
        foreach ($keys as $key) {
            if (!in_array($key, $ignoredList)) {
                $option .= "<option value='" . $key . "'>" . Util::rewriteDBField($key, $keyTerm, $rewriteVirtualField) . "</option>";
            }
        }
        return $option . "</select>";
    }

    /**
     * List brand for product search
     */
    public static function listBrand() {
        $brand = Brand::model()->findAll();
        $list = "<select name='searchOptionBrand' id='searchOptionBrand'><option value='all'>" . Util::t('All') . "</option>";
        foreach ($brand as $key => $value) {
            $list .= "<option value='" . $value->id . "'>" . $value->name . "</option>";
        }
        return $list .= "</select>";
    }

    /**
     * Add/Update object properties fields
     * @objectModel: Identify object which need to be add/update properties
     * @objectID: Identify object ID in Specification Table for action
     */
    public static function addDynamicField($objectModel, $objectID) {
        if (isset($_POST['group']) && isset($_POST['name'])) {
            $existFieldGroup = FieldGroup::model()->find(array(
                'condition' => 'model=:model AND name=:name',
                'params' => array(
                    ':model' => $objectModel,
                    ':name' => $_POST['group'],
                )
                    ));

            //fieldgroup term exist
            if ($existFieldGroup != null) {
                $modelField = new ProductField;
                $modelField->field_group_id = $existFieldGroup->id;
                $modelField->name = $_POST['name'];
                $modelField->weight = 0;

                if ($modelField->save()) {
                    $value = array($_POST['name'] => $_POST['value']);
                    $specification = new Specification;
                    $specification->model = $objectModel;
                    $specification->product_id = $objectID;
                    $specification->value = serialize($value);
                }
                echo "Append";
            } else {   //insert new fieldgroup, productfield, specification
                $modelFieldGroup = new FieldGroup;
                $modelFieldGroup->model = $objectModel;
                $modelFieldGroup->taxonomy_id = 0;
                $modelFieldGroup->name = $_POST['group'];
                $modelFieldGroup->weight = 0;

                if ($modelFieldGroup->save()) {
                    $modelField = new ProductField;
                    $modelField->field_group_id = $modelFieldGroup->id;
                    $modelField->name = $_POST['name'];
                    $modelField->weight = 0;

                    if ($modelField->save()) {
                        $value = array($_POST['name'] => $_POST['value']);
                        $specification = new Specification;
                        $specification->model = $objectModel;
                        $specification->product_id = $objectID;
                        $specification->value = serialize($value);
                    }
                }
                echo "Insert";
            }
        }
    }

    /**
     * Load level available amount belong to start 
     */
    public static function availableDebt() {
        Yii::import('application.modules.setting.models.Variable');
        $config = Variable::model()->findByPk('config');
        $configValue = unserialize($config->value);

        for ($i = 1; $i < 6; $i++) { //default 5 level start in customer level
            switch ($i) {
                case 1:
                    $amount = "'" . number_format($configValue['one_start'], 0, ' ', ' ') . "', ";
                    break;
                case 2:
                    $amount .= "'" . number_format($configValue['two_start'], 0, ' ', ' ') . "', ";
                    break;
                case 3:
                    $amount .= "'" . number_format($configValue['three_start'], 0, ' ', ' ') . "', ";
                    break;
                case 4:
                    $amount .= "'" . number_format($configValue['four_start'], 0, ' ', ' ') . "', ";
                    break;
                case 5:
                    $amount .= "'" . number_format($configValue['five_start'], 0, ' ', ' ') . "'";
                    break;
            }
        }

        return $amount;
    }

    /**
     * list all user except admin for create role access in UserRoleController
     */
    public static function listUsers() {
        $users = User::model()->findAll(array(
            'select' => 't.id, CONCAT(profiles.lastname,\' \', profiles.firstname) as fullname',
            'join' => 'JOIN profiles ON profiles.user_id = t.id JOIN auth_assignment ON auth_assignment.userid = t.id',
            'condition' => 'auth_assignment.itemname <> \'Administrator\''
                ));

        return CHtml::listData($users, 'id', 'fullname');
    }

    /**
     * list all role name
     */
    public static function listRolesName() {
        $role = User::model()->findAll(array(
            'select' => 'auth_assignment.itemname',
            'join' => 'JOIN auth_assignment ON  auth_assignment.userid = t.id',
            'condition' => 'auth_assignment.itemname <> \'Administrator\'',
                ));

        return CHtml::listData($role, 'itemname', 'itemname');
    }

    /**
     * check user role 
     */
    public static function isAllowProcess($userID, $role, $controllerName, $controllerAction) {
        if ($role == 'Administrator')
            return 1;
        else
            $role = UserRole::model()->findAll(array(
                'select' => 'controller_action',
                'condition' => 'user_id = :userID AND controller_name = :controllerName AND role = :role AND controller_action = :controllerAction AND status = 1',
                'params' => array(
                    ':userID' => $userID,
                    ':role' => $role,
                    ':controllerAction' => $controllerAction,
                    ':controllerName' => $controllerName
                )
                    ));
        return $role;
    }

    public static function getUserRole($userID) {
        Yii::import('application.modules.admin.models.AuthAssignment');
        $userRole = AuthAssignmentBase::model()->find(array(
            'condition' => 'userid = :userID',
            'params' => array(
                ':userID' => $userID
            ),
                ));

        if ($userRole)
            return $userRole->itemname;
        else
            return null;
    }

    public static function generalTableID($table, $key) {
        $criteria = new CDbCriteria();
        $criteria->order = $key . ' DESC';
        $criteria->limit = 1;
        //var_dump($table->find($criteria)->$key);
        return $table->find($criteria)->$key;
    }

    public static function getDaysInWeek($weekNumber, $year) {
        // Count from '0104' because January 4th is always in week 1
        // (according to ISO 8601).
        $time = strtotime($year . '0104 +' . ($weekNumber - 1)
                . ' weeks');
        // Get the time of the first day of the week
        $mondayTime = strtotime('-' . (date('w', $time) - 1) . ' days', $time);
        // Get the times of days 0 -> 6
        $dayTimes = array();
        for ($i = 0; $i < 7; ++$i) {
            $dayTimes[] = strtotime('+' . $i . ' days', $mondayTime);
        }
        // Return timestamps for mon-sun.
        return $dayTimes;
    }
    
    public static function getUserList(){
        $users = User::model()->findAll();
        return CHtml::listData($users, 'userid', 'username');
    }

	public static function base32_encode($string){
        $encode = include_once Yii::getPathOfAlias('webroot') . "/protected/extensions/base32/class.base32.php5";
        $encode = new Base32;
        return $encode->fromString($string);
    }
    
    public static function base32_decode($encodeString){
        $encode = include_once Yii::getPathOfAlias('webroot') . "/protected/extensions/base32/class.base32.php5";
        $encode = new Base32;
        return $encode->toString($encodeString);
    }    
}
